var url = require('url');
var doubanApi = require('../lib/doubanApi');
var config = require('./config');

// doubanApi.init({
//   app_key: APP_KEY,
//   app_secret: APP_SECRET,
//   app_redirect_uri: APP_REDIRECT_URI
// });
doubanApi.init(config.douban_app_info);

module.exports = {
    hello: function (req, res) {
        var html = [];
        var uid = req.session.uid;
        var nickname = req.session.nickname || 'nodejs';
        var avatar = req.session.avatar;
        if (req.session.access_token) {
            html.push('<p>' + req.session.access_token + '</p>');
            html.push('<p><img src="' + avatar + '" /> hello ' + nickname + '.</p>');
            html.push('<p><a href="./create">Create</a></p>');
            html.push('<p><a href="./api/followers?uid=' + uid + '">My Followers</a></p>');
            html.push('<p><a href="./api/home-timeline">Timeline</a></p>');
            html.push('<p><a href="./logout">Logout</a></p>');
        } else {
            html.push('<p>hello ' + nickname + '.</p>');
            html.push('<p><a href="./oauth"><img src="/static/img/32.png" /></a></p>');
        }
        render(res, 200, 'text/html', html.join(''));
    },


    oauth: function (req, res) {
        doubanApi.authorize(res);
    },


    callback: function (req, res) {
        var query = url.parse(req.url, true).query; // true makes query to json
        if (query.code) {
            doubanApi.accessToken(query.code, function (err, data) {
                if (data.error) {
                    json(res, {
                        error: data.error_description,
                        data: null
                    });
                } else {
                    // json(res, {
                    //   error: err,
                    //   data: data
                    // });
                    req.session.uid = data.douban_user_id;
                    req.session.nickname = data.douban_user_name;
                    req.session.access_token = data.access_token;
                    doubanApi.access_token = data.access_token;
                    doubanApi.userGetByUid(data.douban_user_id, function (err, data) {
                        // json(res, {
                        //   error: err,
                        //   data: data
                        // });
                        req.session.avatar = data.avatar;
                        redirect(res, './hello');
                    });
                    // doubanApi.userGetByName(data.douban_user_name, function (err, data) {
                    //     // json(res, {
                    //     //   error: err,
                    //     //   data: data
                    //     // });
                    //     req.session.nickname = data.name;
                    //     req.session.avatar = data.avatar;
                    //     redirect(res, './hello');
                    // });
                }
            });
        } else {
            json(res, {
                error: 'code lost',
                data: null
            });
        }
    },


    logout: function (req, res) {
        req.session = null;
        redirect(res, './hello');
    },

    apiFollowers: function (req, res) {
        var query = url.parse(req.url, true).query; // true makes query to json
        if (query.uid) {
            doubanApi.usersFollowers(query.uid, function (err, data) {
                json(res, {
                    error: err,
                    data: data
                });
            });
        }
    },

    apiHomeTimeline: function (req, res) {
        var query = url.parse(req.url, true).query; // true makes query to json
        var count = query.count || 10;
        doubanApi.statusesHomeTimeline({
            count: count
        }, function (err, data) {
            json(res, {
                error: err,
                data: data
            });
        });
    },

    apiUserTimeline: function (req, res) {
        var query = url.parse(req.url, true).query; // true makes query to json
        doubanApi.statusesUserTimeline(query.uid, function (err, data) {
            json(res, {
                error: err,
                data: data
            });
        });
    },

    apiStatusesPost: function (req, res) {
        doubanApi.statusesPost({
            // source: '0e119e3f962eeb322a34dabec28cc196',     // appkey
            text: '广播文本内容',
            // image   false   bytes   我说的图
            rec_title: 'CafeInit',
            rec_url: 'http://www.cafeinit.com',
            rec_desc: '一个有关咖啡的网站',
            rec_image: 'http://img5.douban.com/view/photo/photo/public/p1425585869.jpg'
        }, function (err, data) {
            json(res, {
                error: err,
                data: data
            });
        });
    }
};


function json (res, obj) {
    res.writeHead(200, {
        'Content-Type': 'application/json; charset=utf-8'
    });
    res.write(JSON.stringify(obj));
    res.end();
}


function render (res, code, type, content) {
    res.writeHead(code, {
        'Content-Type': type + '; charset=utf-8'
    });
    var header = '<!DOCTYP html><html><head><meta charset="utf-8"></head><body>';
    var footer = '</body></html>';
    res.write(header + content + footer);
    res.end();
}


function redirect (res, url) {
    res.writeHead(302, {
        'Location': url
        //add other headers here...
    });
    res.end();
}
